<template>
  <div id="bonusDetailPage">
    <!-- 麵包屑導航 -->
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />

    <!-- 消息詳情卡片 -->
    <a-space direction="vertical" style="width: 100%">
      <a-card title="基本參數" class="detail-card" :loading="loading1">
        <template v-if="bonus.id">
          <a-descriptions bordered>
            <a-descriptions-item label="獎金名稱">
              {{ bonus.bonusName }}
            </a-descriptions-item>
            <a-descriptions-item label="統計月份">
              {{ bonus.statMonth }}
            </a-descriptions-item>
            <a-descriptions-item label="店鋪">
              {{ bonus.shopName }} ({{ bonus.shopId }})
            </a-descriptions-item>

            <a-descriptions-item label="醫師名稱">
              {{ bonus.doctorName }}
            </a-descriptions-item>
            <a-descriptions-item label="員工編號">
              {{ bonus.staffCode }}
            </a-descriptions-item>
            <a-descriptions-item label="指定銷售產品Teams">
              <a-tag
                v-for="team in bonus.productTeams"
                :key="team"
                color="blue"
              >
                {{ team }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="指定產品總銷售金額">
              $ {{ bonus.totalSalesAmount.toLocaleString() }}
            </a-descriptions-item>

            <a-descriptions-item label="指定產品店銷售金額">
              $ {{ bonus.shopSalesAmount.toLocaleString() }}
            </a-descriptions-item>

            <a-descriptions-item label="指定產品店銷售金額佔比">
              {{
                (
                  (bonus.shopSalesAmount / bonus.totalSalesAmount) *
                  100
                ).toFixed(2)
              }}%
            </a-descriptions-item>

            <a-descriptions-item label="可獲獎金金額">
              <template v-if="isDoctor && !bonus.isArchived">待計算</template>
              <template v-else
                >$ {{ bonus.bonusAmount.toLocaleString() }}</template
              >
            </a-descriptions-item>

            <a-descriptions-item label="開始日期">
              {{ bonus.startDate }}
            </a-descriptions-item>
            <a-descriptions-item label="結束日期">
              {{ bonus.endDate }}
            </a-descriptions-item>
            <a-descriptions-item label="狀態">
              <a-tag
                :bordered="false"
                color="success"
                v-if="bonus.isArchived == true"
                >已歸檔</a-tag
              >
              <a-tag :bordered="false" color="processing" v-else>未歸檔</a-tag>
            </a-descriptions-item>

            <a-descriptions-item label="更新時間">{{
              $formatDate(bonus.updatedAt)
            }}</a-descriptions-item>
          </a-descriptions>
        </template>
        <template v-else>
          <a-empty description="數據加載失敗，請重試" />
        </template>
      </a-card>

      <a-card title="相關發票列表">
        <a-table
          :columns="columns"
          :data-source="tableData"
          :pagination="pagination"
          :loading="loading2"
        >
          <!-- 表格頭部 -->
          <template #headerCell="{ column }">
            <!-- 根據表頭字段進行表頭修飾 -->
          </template>

          <!-- 表格內容 -->
          <template #bodyCell="{ column, record }">
            <!-- 根據不同的列顯示不同的內容修飾 -->
            <template v-if="column.dataIndex === 'totalAmount'">
              $ {{ record.totalAmount.toLocaleString() }}
            </template>

            <template v-if="column.key === 'action'">
              <a-button @click="handleView(record)">查看</a-button>
            </template>
          </template>
        </a-table>
      </a-card>

      <!-- 操作按鈕 -->
      <BackButton />
    </a-space>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { bonusApi } from "@/api";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";
import BackButton from "@/components/BackButton.vue";
import { createPagination } from "@/utils/pagination";
import { watchRouteQuery } from "@/utils/routeQueryWatcherUtil";
import { useAuthUserStore } from "@/store/authUserStore";

const route = useRoute();
const router = useRouter();
const userInfo = useAuthUserStore().userInfo;
const isDoctor = userInfo.roles.includes("Doctor");

// 分頁配置
const pagination = createPagination();
// 數據
const tableData = ref([]);

const columns = [
  { title: "發票號", dataIndex: "invNo" },
  { title: "指定產品銷售總金額", dataIndex: "totalAmount" },
  { title: "銷售日期", dataIndex: "invDate" },
  { title: "操作", key: "action", align: "center" },
];

// 麵包屑導航
const breadcrumbItems = [
  { url: "/bonus", name: "獎金列表" },
  { url: "", name: "詳情" },
];

// 消息詳情數據
const bonus = ref<any>({});
const loading1 = ref(true);
const bonusId = Number(route.params.id);

// 獲取消息詳情
const fetchDetail = async () => {
  try {
    loading1.value = true;
    const { data } = await bonusApi.getBonusDetail(bonusId);
    bonus.value = data;
  } catch (error) {
    console.error("獲取詳情失敗", error);
  } finally {
    loading1.value = false;
  }
};

const loading2 = ref(true);
const fetchInvoiceList = async (params?: any) => {
  loading2.value = true; // 開始加載
  try {
    const {
      data: { list, page, limit, total },
    } = await bonusApi.getInvoiceList(bonusId, params);
    tableData.value = list || [];
    pagination.updatePagination(page, limit, total);
  } catch (error) {
    console.error("獲取獎金列表失敗", error);
  } finally {
    loading2.value = false; // 結束加載
  }
};

watchRouteQuery(fetchInvoiceList);

// 初始化加載
onMounted(() => {
  fetchDetail();
});

// const bonusLevelColumns = tableColumns

const handleView = (record: any) => {
  router.push({ name: "InvoiceDetail", params: { invNo: record.invNo } });
};
</script>

<style scoped></style>
